package com.hankol.newretail

import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.MarginDecoration
import com.google.android.material.appbar.AppBarLayout
import com.baselibrary.activity.BaseActivity
import com.baselibrary.utils.EmptyViewUtil
import com.hankol.newretail.adapter.StoreGoodsAdapter
import com.hankol.newretail.bean.GoodListBean
import com.hankol.newretail.databinding.ActivityPaySuccessBinding
import com.hankol.newretail.viewmodel.SelectPayStyleViewModel
import com.media.publish.utils.CommonBusiness


/**
 * @description 支付成功
 *@author wxp
 */
@Route(path = ActivityRouter.NEW_RETAIL.PAY_SUCCESS)
class PaySuccessActivity : BaseActivity(), View.OnClickListener {

    var page = 1
    private var hasnext: Boolean = false
    private val adapter by lazy { StoreGoodsAdapter() }
    private lateinit var binding: ActivityPaySuccessBinding
    private lateinit var mViewModel: SelectPayStyleViewModel

    //曝光数
    var exposureCnt = 0

    //id数组字符串
    var ids = ""
    var payPriceSum = "0"
    var scoreDeductPriceSum = "0"
    var shouldRewardScore = "0"

    companion object {
        //key 购买数量（从商品详情进入）
        const val KEY_POIDS = "poids"
        const val KEY_PAY_PRICE_SUM = "payPriceSum"
        const val KEY_SCORE_DEDUCTPRICE_SUM = "scoreDeductPriceSum"
        const val KEY_SHOULD_REWARD_SCORE = "shouldRewardScore"
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_pay_success
    }

    override fun init() {
        //获取页面开始时间
        SensorsDataManager.instance.onCreateTime()
        binding = getDataBinding<ActivityPaySuccessBinding>()
        initImmersion(true)
        mViewModel = getActivityViewModelProvider(this).get(SelectPayStyleViewModel::class.java)
        if (intent.extras.checkNotNull()) {
            if (ARouterUtils.parseParams(intent.extras!!, KEY_POIDS).isNotEmpty()) {
                ids = ARouterUtils.parseParams(intent.extras!!, KEY_POIDS)[0].checkValue()
            }
            if (ARouterUtils.parseParams(intent.extras!!, KEY_PAY_PRICE_SUM).isNotEmpty()) {
                payPriceSum = ARouterUtils.parseParams(intent.extras!!, KEY_PAY_PRICE_SUM)[0].checkValue()
            }
            if (ARouterUtils.parseParams(intent.extras!!, KEY_SCORE_DEDUCTPRICE_SUM).isNotEmpty()) {
                scoreDeductPriceSum = ARouterUtils.parseParams(intent.extras!!, KEY_SCORE_DEDUCTPRICE_SUM)[0].checkValue()
            }
            if (ARouterUtils.parseParams(intent.extras!!, KEY_SHOULD_REWARD_SCORE).isNotEmpty()) {
                shouldRewardScore = ARouterUtils.parseParams(intent.extras!!, KEY_SHOULD_REWARD_SCORE)[0].checkValue()
            }
        }
        initView()
        initListener()
        initObserver()
        setDataInfo()
    }

    private fun initView() {
        binding.smartRefresh.setEnableRefresh(false)
        binding.rvGoodList.layoutManager = GridLayoutManager(this, 2)
        binding.rvGoodList.addItemDecoration(MarginDecoration(this, 9))
        binding.rvGoodList.adapter = adapter
        //曝光监听
        binding.rvGoodList.addOnScrollListener(object : RecyclerViewExposureListener() {
            override fun exposureView(view: View?, index: Int) {
                exposureCnt = index.plus(2)
            }
        })
    }

    private fun initObserver() {

        mViewModel.guessYouLikeLD.observe(this, Observer {
            hideLoadingDialog()
            binding.smartRefresh.finishRefresh()
            if (it.data.size == 0) {
                binding.llGuessLike.visibility = View.GONE
                //无数据
                if (page != 1) {
                    binding.smartRefresh.finishLoadMore()
                }
                adapter.emptyView = EmptyViewUtil.getEmptyView(Constants.TYPE_GOOD_LIST, binding.rvGoodList, "暂无商品")
            } else {
                if (it.data.checkNotNull()) {
                    binding.llGuessLike.visibility = View.VISIBLE
                    hasnext = it.hasnext
                    binding.smartRefresh.finishLoadMore()
                    if (page == 1) {
                        adapter.setNewData(it.data)
                    } else {
                        adapter.addData(it.data)
                    }
                    page++
                } else {
                    binding.smartRefresh.finishLoadMore()
                }
            }

        })

    }

    private fun initListener() {
        binding.backImageView.setOnClickListener { finish() }
        binding.ablTop.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            val offset = ScreenUtils.dpToPx(158) /*+ binding.tvPeriodsPlayNum.height*/
            if (-verticalOffset in 0..offset) {
                binding.rlTopTitle.visibility = View.GONE
            } else {
                binding.rlTopTitle.visibility = View.VISIBLE
            }
        })
        adapter.setOnItemClickListener { adapter, view, position ->
            if (!DoubleUtils.isFastDoubleClick()) {
                val bean = adapter.data[position] as GoodListBean
                //进入对应详情页面
                val map = java.util.HashMap<String, Any>()
                map[Constants.GOODS_DETAIL_ID] = bean.id
                map[Constants.GOODS_DETAIL_SOURCE] = "支付成功页猜你喜欢"
                ARouterUtils.jump(ActivityRouter.NEW_RETAIL.GOODS_DETAUILS, map)
            }
        }

        binding.smartRefresh.setOnRefreshListener {
            page = 1
            loadGuessLikeData()
        }
        binding.smartRefresh.setOnLoadMoreListener {
            if (hasnext) {
                loadGuessLikeData()
            } else {
                binding.smartRefresh.finishLoadMore()
            }
        }
        binding.includeTop.tvSeeOrder.setOnClickListener(this)
    }

    fun loadGuessLikeData() {
        showLoadingDialog()
        mViewModel.reqGuessYouLikeGoodList(ids, page)
    }

    private fun setDataInfo() {
        //实付款
        binding.includeTop.tvRealPrice.text = "¥${AmountUtil.changeF2YKeepTwo("${payPriceSum}")}"
        binding.includeTop.tvCoinPrice.text = "¥${AmountUtil.changeF2YKeepTwo("${scoreDeductPriceSum}")}"
        binding.includeTop.tvShouldRewardScore.text = "确认收货后，预计获赠${shouldRewardScore}酒币"
        binding.includeTop.tvShouldRewardScore.visibility = if (shouldRewardScore.toInt() > 0) View.VISIBLE else View.GONE
        binding.includeTop.tvCoinTitle.visibility = if (scoreDeductPriceSum.toInt() > 0) View.VISIBLE else View.GONE
        binding.includeTop.tvCoinPrice.visibility = if (scoreDeductPriceSum.toInt() > 0) View.VISIBLE else View.GONE

        loadGuessLikeData()
        CommonBusiness.shareSuccess(this, 5,"支付成功")
    }


    override fun onPause() {
        super.onPause()
        //获取页面结束时间
        SensorsDataManager.instance.onDestroyTime()
        if (SensorsDataManager.instance.getBrowseTime() != 0L) {
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //获取页面结束时间
        SensorsDataManager.instance.onDestroyTime()
        if (SensorsDataManager.instance.getBrowseTime() != 0L) {
        }

    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.tv_see_order -> {
                //查看订单
                if (ids.checkNotNull()) {
                    val poidList = CommonUtil.jsonToList(ids, String::class.java)
                    if (poidList.size > 1) {
                        //多店铺
                        // 跳转到待发货订单列表
                        val map = java.util.HashMap<String, Any>()
                        map[Constants.KEY_ORDER_TYPE] = 1
                        ARouterUtils.jump(ActivityRouter.NEW_RETAIL.MY_ORDER, map)
                    } else {
                        val hashMap = HashMap<String, Any>()
                        hashMap[Constants.KEY_ORDER_ID] = poidList[0]
                        ARouterUtils.jump(ActivityRouter.NEW_RETAIL.ORDER_DETAIL, hashMap)
                    }
                    finish()
                }
            }
        }
    }
}